import { Input, Select, Table, Checkbox, Button, Breadcrumb, Modal, Form, DatePicker } from 'antd';
import css from './Good.module.css';
import { useEffect, useState } from 'react';
import axios from 'axios'; 
import moment from 'moment'; 
import {PlusOutlined} from '@ant-design/icons';

// 添加商品弹窗组件
const AddGoodsModal = ({ visible, onCancel, onSave }) => {
  const [form] = Form.useForm();

  // 新增状态变更处理函数
  const handleStatusChange = (value) => {
    if (value === '待支付') {
      form.setFieldsValue({ pay: null });
    }
  };

  return (
    <Modal
      title="添加订单"
      visible={visible}
      onCancel={() => {
        form.resetFields();
        onCancel();
      }}
      onOk={() => form.submit()}
      okText="创建"
      cancelText="取消"
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={onSave}
        preserve={false}
      >
        <Form.Item
          label="订单编码"
          name="productCode"
          rules={[{ required: true, message: '请输入订单编码!' }]}
        >
          <Input placeholder="例: #23ANZX29" />
        </Form.Item>

        <Form.Item
          label="订单名称"
          name="productName"
          rules={[{ required: true, message: '请输入订单名称!' }]}
        >
          <Input placeholder="例: iPhone 13" />
        </Form.Item>
        <Form.Item
            label="付款类型"
            name="pay" 
            dependencies={['status']}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (getFieldValue('status') !== '待支付' && !value) {
                    return Promise.reject('请选择支付方式!');
                  }
                  return Promise.resolve();
                },
              }),
            ]}
            >
              <Select 
                disabled={form.getFieldValue('status') === '待支付'}
                allowClear={form.getFieldValue('status') !== '待支付'}
              >
                <Select.Option value="微信">微信</Select.Option>
                <Select.Option value="支付宝">支付宝</Select.Option>
            </Select>
        </Form.Item>
        <Form.Item
          label="订单价格"
          name="price"
          rules={[
            { required: true, message: '请输入价格!' },
            () => ({
              validator(_, value) {
                if (value >= 0) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('价格不能为负数!'));
              },
            }),
          ]}
          normalize={(value) => Number(value)} // 自动转换为数字
        >
          <Input type="number" prefix="¥" />
        </Form.Item>

        <Form.Item
          label="订单时间"
          name="listingDate"
          rules={[{ required: true, message: '请选择订单时间!' }]}
        >
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm"
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item
          label="订单状态"
          name="status"
          initialValue="待支付"
          rules={[{ required: true, message: '请选择订单状态!' }]}
        >
          <Select onChange={handleStatusChange}>
            <Select.Option value="待支付">待支付</Select.Option>
            <Select.Option value="待发货">待发货</Select.Option>
            <Select.Option value="已完成">已完成</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

function Order() {
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [originData, setOriginData] = useState([]);      // 原始数据
  const [filteredData, setFilteredData] = useState([]);  // 筛选后的数据
  const [modalVisible, setModalVisible] = useState(false);  // 新增弹框显示状态
  const [filters, setFilters] = useState({
    pageSize: 10,
    status: 'all',
    searchKeyword: ''
  });

// 处理表单提交
const handleAddGoods = async (values) => {
  try {
    // 格式化日期
    const formattedValues = {
      ...values,
      listingDate: values.listingDate.format('YYYY-MM-DD HH:mm'),
      price: Number(values.price),
      pay: values.status === '待支付' ? null : values.pay
    };

    // 调用后端API
    await axios.post('http://localhost:3000/Order', formattedValues);
    
    // 刷新数据
    const response = await axios.get('http://localhost:3000/Order');
    setOriginData(response.data.data);
    setFilteredData(response.data.data);
    
    setModalVisible(false);
    message.success('商品添加成功！');
  } catch (error) {
    console.error('添加失败:', error.response?.data); // 显示详细错误信息
    message.error(`添加失败: ${error.response?.data?.message || '服务器错误'}`);
  }
};

  // 从后端获取数据
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const response = await axios.get('http://localhost:3000/Order');
        setOriginData(response.data.data);
        setFilteredData(response.data.data); // 初始化筛选数据
      } catch (error) {
        console.error("数据加载失败:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  // 监听状态变化
  const handleFilterStatusChange = (value) => {
    setFilters(prev => ({
      ...prev,
      status: value
    }));
  };

   // 处理筛选变化
   useEffect(() => {
    applyFilters();
    console.log('当前筛选条件:', filters);
    console.log('筛选后数据量:', filteredData.length);
  }, [filters, originData]);

  // 筛选逻辑
const applyFilters = () => {
  let result = [...originData];
  
  try {
    // 状态筛选
    if (filters.status && filters.status !== 'all') {
      result = result.filter(item => 
        item.status?.toLowerCase() === filters.status?.toLowerCase()
      );
    }

    // 搜索筛选
    if (filters.searchKeyword) {
      const keyword = filters.searchKeyword.toLowerCase().trim();
      result = result.filter(item => 
        item.productName?.toLowerCase().includes(keyword)
      );
    }
  } catch (error) {
    console.error('筛选出错:', error);
  }

  setFilteredData(result);
};

  // 处理显示数量变化
  const handlePageSizeChange = (value) => {
    setFilters(prev => ({
      ...prev,
      pageSize: Number(value)
    }));
  };

  // 全选/反选逻辑
  const handleSelectAll = (checked) => {
    const currentPageKeys = filteredData.map(item => item.productCode);
    setSelectedRowKeys(checked ? currentPageKeys : []);
  };

  // 表格列配置
  const columns = [
    {
      title: (
        <Checkbox
          indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < filteredData.length}
          checked={selectedRowKeys.length === filteredData.length && filteredData.length > 0}
          onChange={e => handleSelectAll(e.target.checked)}
        />
      ),
      key: 'selection',
      width: 60,
      render: (_, record) => (
        <Checkbox
          checked={selectedRowKeys.includes(record.productCode)}
          onChange={e => {
            const keys = e.target.checked
              ? [...selectedRowKeys, record.productCode]
              : selectedRowKeys.filter(key => key !== record.productCode);
            setSelectedRowKeys(keys);
          }}
        />
      )
    },
    { title: '订单编码', dataIndex: 'productCode', key: 'productCode' },
    { title: '订单名称', dataIndex: 'productName', key: 'productName' },
    {
        title: '付款类型',
        dataIndex: 'pay', 
        key: 'pay',
        render: (pay, record) => {
          if (record.status === "待支付") return "-"; // 状态为待支付时显示占位符
          return pay === "微信" ? "✅ 微信支付" : "💳 支付宝支付";
        }
    },
    { 
      title: '订单价格', 
      dataIndex: 'price', 
      key: 'price',
      render: (value) => `¥${value.toFixed(2)}` // 格式化为人民币金额
    },
    { 
      title: '订单时间', 
      dataIndex: 'listingDate', 
      key: 'listingDate',
      render: (date) => moment(date).format('YYYY-MM-DD HH:mm') // 格式化日期
    },
    { 
        title: '订单状态', 
        dataIndex: 'status', 
        key: 'status',
        render: (status) => {
          switch(status) {
            case "已完成": return "✅ 已完成";
            case "待发货": return "🚚 待发货";
            case "待支付": return "⏳ 待支付";
          }
        }
      },
  ];

  return (
    <div className={css.container} style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 头部 */}
      <div className={css.header}>
        <h1 className={css.maintitle}>订单</h1>
        <Breadcrumb
          className={css.breadcrumb}
          items={[
            { title: '电子商务' },
            { title: '订单' }
          ]}
        />
      </div>

      {/* 操作栏 */}
      <div className={css.actionbar}>
        <div className={css.filters}>
          <span className={css.filterlabel}>显示</span>
          <Select
            value={filters.pageSize}
            defaultValue="10"
            className={css.filterselect}
            onChange={handlePageSizeChange}
            options={[{ value: '5', label: '5' },{ value: '10', label: '10' }]}
          />
          
          <span className={css.filterlabel}>状态</span>
          <Select
            defaultValue="all"
            value={filters.status}
            className={css.filterselect}
            onChange={handleFilterStatusChange} 
            options={[
              { value: 'all', label: '所有状态' },
              { value: '已完成', label: '已完成' },
              { value: '待发货', label: '待发货' },
              { value: '待支付', label: '待支付' },
            ]}
          />
        </div>

        <div className={css.searchgroup}>
          <Input
            placeholder="搜索商品"
            className={css.searchinput}
            allowClear
            style={{ flex: 1 }}
            onChange={(e) => setFilters(prev => ({
              ...prev,
              searchKeyword: e.target.value
            }))}
          />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              style={{ 
                background: '#1890ff', 
                borderColor: '#1890ff',
                height: '32px' 
              }}
              onClick={() => setModalVisible(true)}
            />
        </div>
      </div>

      {/* 数据表格 */}
      <div style={{ flex: 1, overflow: 'hidden' }}>
        <Table
          columns={columns}
          dataSource={filteredData}
          bordered
          className={css.datatable}
          loading={loading}
          rowKey="productCode" // 使用唯一标识作为 key
          pagination={{
            pageSize: filters.pageSize,
            showSizeChanger: false,
            showTotal: total => `共 ${total} 条`
          }}
        />
      </div>
      {/* 添加弹窗组件 */}
      <AddGoodsModal
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onSave={handleAddGoods}
      />
    </div>
  )
}

export default Order;